package com.zhenwgang.listen_books.servlet.track;

import com.zhenwgang.listen_books.repository.TrackRepo;
import com.zhenwgang.listen_books.util.Log;
import com.zhenwgang.listen_books.view_object.UserVO;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author Violet
 * @date 2022/07/12 09:49
 **/
@WebServlet("/studio/track/record.json")
public class RecordJsonServlet  extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final TrackRepo trackRepo = new TrackRepo();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        String type = req.getHeader("Content-Type");
        Log.println(title);
        Log.println(type);

        UserVO currentUser = null;
        HttpSession session = req.getSession(false);
        if (session != null){
            currentUser = (UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();

        if (currentUser == null){
            Log.println("用户未登录");
            HashMap<String, Boolean> result = new HashMap<>();
            result.put("result", false);
            String json = objectMapper.writeValueAsString(result);
            Log.println(json);
            writer.println(json);
            return;
        }

        trackRepo.insert(currentUser.uid, title, type, req.getInputStream());
        Log.println("将数据保存在数据库中");

        Log.println("用户已登录");
        HashMap<String, Boolean> result = new HashMap<>();
        result.put("result", true);
        String json = objectMapper.writeValueAsString(result);
        Log.println(json);
        writer.println(json);
    }
}